package com.entrogy.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.entrogy.bean.BusLineEntity;
import com.entrogy.bean.PubCountEntity;
import com.entrogy.bean.UserEntity;
import com.entrogy.dao.BusLineMapper;
import com.entrogy.dao.SchoolMapper;
import com.entrogy.dao.StudentMapper;
import com.entrogy.dao.UserMapper;
import com.entrogy.service.BusLineService;
import com.entrogy.utils.SendUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @ClassName BudLineServiceImpl
 * @Description
 * @Author luoxingjiang
 * @Date 2019-11-08 上午 10:08
 * @Version 1.0
 **/
@Service
public class BudLineServiceImpl implements BusLineService {

    private Logger logger = LoggerFactory.getLogger(BudLineServiceImpl.class);

    @Autowired
    private BusLineMapper busLineMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private SchoolMapper schoolMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<BusLineEntity> listSchoolBusLine(Integer schoolCode) {
        return busLineMapper.listSchoolBusLine(schoolCode);
    }

    @Override
    public boolean insertBusLine(BusLineEntity busLine) {
        return busLineMapper.insertBusLine(busLine) == 1;
    }

    @Transactional
    @Override
    public boolean deleteBusLine(Integer busLineId, String userId) {
        int updateAllSchoolStudentBusLineRow = busLineMapper.updateAllSchoolStudentBusLine(String.valueOf(busLineId));
        int deleteBusLineRow = busLineMapper.deleteBusLine(busLineId, userId);
        return true;
    }

    @Override
    public boolean updateBusLine(BusLineEntity busLine) {
        return busLineMapper.updateBusLine(busLine) > 0;
    }

    @Override
    public boolean sendMessage(List<Integer> studentIdList, Integer type, String userId) {
        List<JSONObject> sendInfoList = studentMapper.listParentOpenId(studentIdList);
        UserEntity user = userMapper.getUserByUid(userId);
        sendInfoList.forEach(sendInfo -> {
            String schoolName = schoolMapper.getSchoolName(user.getSchoolCode());
            String[] paramsWeiXin = { "",  schoolName, user.getName(), new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date()), ""};
            paramsWeiXin[4] = "您的孩子《" + sendInfo.getString("studentName") + "》，已坐上校车准备" + (type == 3 ? "回家" : "去学校") +"，请关注孩子安全！";
            SendUtils.sendByWeixin(new PubCountEntity(sendInfo.getString("openId"),sendInfo.getString("accessToken")), paramsWeiXin, sendInfo.getString("templateId"));
        });
        return true;
    }

    @Override
    public Integer countSchoolBusLine(Integer schoolCode) {
        return busLineMapper.countSchoolBusLine(schoolCode);
    }
}
